-- Lua 脚本：智能提取和标准化日志级别
-- 用于在 Fluent Bit FILTER 阶段处理日志数据

function extract_log_level(tag, timestamp, record)
    local message = record["message"] or record["log"] or ""
    local level = "info"  -- 默认级别
    
    -- 智能识别日志级别
    local msg_lower = string.lower(message)
    
    if string.match(msg_lower, "fatal") or string.match(msg_lower, "panic") then
        level = "fatal"
    elseif string.match(msg_lower, "error") or string.match(msg_lower, "err") or string.match(msg_lower, "exception") then
        level = "error"
    elseif string.match(msg_lower, "warn") or string.match(msg_lower, "warning") then
        level = "warn"
    elseif string.match(msg_lower, "debug") or string.match(msg_lower, "trace") then
        level = "debug"
    elseif string.match(msg_lower, "info") then
        level = "info"
    end
    
    -- 检查是否已经有 level 字段，如果没有则添加
    if not record["level"] and not record["log_level"] then
        record["log_level"] = level
    end
    
    -- 标准化时间戳格式
    if record["time"] and not record["@timestamp"] then
        record["@timestamp"] = record["time"]
    end
    
    return 2, timestamp, record  -- 返回码2表示仅修改记录
end

function map_systemd_priority(tag, timestamp, record)
    local priority = record["PRIORITY"]
    if priority then
        local level_map = {
            ["0"] = "emergency",
            ["1"] = "alert", 
            ["2"] = "critical",
            ["3"] = "error",
            ["4"] = "warning",
            ["5"] = "notice",
            ["6"] = "info",
            ["7"] = "debug"
        }
        
        local mapped_level = level_map[tostring(priority)]
        if mapped_level then
            record["log_level"] = mapped_level
        end
    end
    
    return 2, timestamp, record
end

-- 处理 Kubernetes 标签中带点的字段
function process_kubernetes_labels(tag, timestamp, record)
    local k8s = record["kubernetes"]
    if k8s and k8s["labels"] then
        -- 提取常用的 Kubernetes 标签
        if k8s["labels"]["app.kubernetes.io/name"] then
            record["app_name"] = k8s["labels"]["app.kubernetes.io/name"]
        end
        
        if k8s["labels"]["app.kubernetes.io/version"] then
            record["app_version"] = k8s["labels"]["app.kubernetes.io/version"]
        end
        
        if k8s["labels"]["app.kubernetes.io/instance"] then
            record["service_name"] = k8s["labels"]["app.kubernetes.io/instance"]
        end
        
        if k8s["labels"]["app.kubernetes.io/component"] then
            record["component"] = k8s["labels"]["app.kubernetes.io/component"]
        end
    end
    
    return 2, timestamp, record
end